<?php
namespace app\web\controller;

use app\common\logic\CouponLogic;
use app\common\model\commonModel;
use app\common\model\trAdmin;
use app\common\model\trAirport;
use app\common\model\trAirportLine;
use app\common\model\trArticle;
use app\common\model\trArticleType;
use app\common\model\trBusesLine;
use app\common\model\trCache;
use app\common\model\trCar;
use app\common\model\trCarLine;
use app\common\model\trCarType;
use app\common\model\trClassesCache;
use app\common\model\trCoupon;
use app\common\model\trDriver;
use app\common\model\trInvoices;
use app\common\model\trOperateLog;
use app\common\model\trOrder;
use app\common\model\trReason;
use app\common\model\trResource;
use app\common\model\trSystemSet;
use app\common\model\trUser;
use app\common\model\trUserToken;
use app\common\model\trVehicleLine;
use app\common\util\ErrorCode;
use app\common\util\Tools;
use think\Db;
use think\facade\Env;

class InitInstallController
{
    public $returnData;
    protected $tableName = "upgrade";
    public function __construct()
    {
        /*--- start 跨域测试用 (待删除) ---*/
        header('Access-Control-Allow-Origin: *');                                                                 // 允许任意域名发起的跨域请求
        header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE');
        header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With,x-requested-with,content-type');
        /*--- end 跨域测试用---*/
        $this->returnData = ErrorCode::$errorCode["success"];
    }

    public function return_result($data, $text = '')
    {
        if(!is_array($data['msg']) && $text && strpos($data['msg'], "%s") !== false){
            $data['msg'] = sprintf($data['msg'], $text);
        }
        return json($data);
    }

    public function initInstall(){
        //创建数据库表
        $db = new \PDO(
            "mysql:host=" . config("database.hostname") . ";port=" . config("database.hostport") . ";charset=" . config("database.charset"),
            config("database.username"), config("database.password")
        );
        $table = $db->query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA where SCHEMA_NAME='" . config("database.database") . "';")->fetch();
        if (empty($table)) {
            // character set：指定编码    COLLATE：排序规则 utf8mb4_general_ci 大小写不敏感
            $sql = "CREATE DATABASE `" . config("database.database")."` default character set utf8mb4 COLLATE utf8mb4_general_ci";
            $db->exec($sql);
        }
        if (empty(Db::query('SHOW TABLES LIKE "tr_user"'))) {
            $sqlFile = Env::get("root_path") . "/mysql.sql";
            $content = file_get_contents($sqlFile);
            $data = explode(";\r\n", $content);
            foreach ($data as $sql) {
                Db::query($sql);
            }
        }
    }

    // 初始化安装数据库
    public function getInstallSqlData(){
        //创建数据库表
        try {
            $this->initInstall();
        }catch (\Exception $e){
            Tools::writeLog(__METHOD__ . "-运行出错11：" . var_export($e->getMessage() . "\r\n" . $e->getLine(), true) . "\r\n" . var_export($e->getTraceAsString(), true), "runLog/runError.txt");
            $this->returnData = ErrorCode::code("try_error", $e->getMessage());
            $this->returnData["msg"] = iconv("GBK", "UTF-8",$this->returnData["msg"]);
        }
        return $this->return_result($this->returnData);
    }

    // 更新数据
    public function getUpgradeData(){
        $count = 16;
        $step = 1;
        try {
            $db = new \PDO(
                "mysql:host=" . config("database.hostname") . ";port=" . config("database.hostport") . ";charset=" . config("database.charset"),
                config("database.username"), config("database.password")
            );
            $table = $db->query("SELECT SCHEMA_NAME FROM information_schema.SCHEMATA where SCHEMA_NAME='" . config("database.database") . "';")->fetch();
            if (empty($table)) {
                $this->initInstall();
                while ($step <= $count) {
                    $method = "upgrade{$step}";
                    if (method_exists($this, $method) && !commonModel::getCount($this->tableName, ["name" => $method, "status" => 1])) { // 执行更新
                        commonModel::toAdd($this->tableName, ["name" => $method, "status" => 1, "create_time" => time()]);
                    }
                    $step++;
                };
            }else {
                if (empty(Db::query('SHOW TABLES LIKE "tr_upgrade"'))) {
                    Db::query("CREATE TABLE `tr_upgrade` (
   `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
   `name` varchar(50) NOT NULL COMMENT '名称',
   `status` char(1) DEFAULT 0 COMMENT '状态',
   `create_time` char(10) NOT NULL COMMENT '创建时间',
   PRIMARY KEY (`id`),
   KEY (`name`),
   KEY (`status`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='版本更新表';");
                }else{
                    try { // 修改表结构
                        \db()->query("alter table tr_upgrade add index (`status`)");
                    }catch (\Exception $e){}
                    try { // 修改表结构
                        \db()->query("alter table tr_upgrade modify column `name` varchar(100) NOT NULL COMMENT '名称'");
                    }catch (\Exception $e){}
                }
                $delTime = 1565322943; // 匹配小于这个时间的数据删除，为了重新从1开始跑脚本
                commonModel::delByFilter($this->tableName, [["create_time", "<=", $delTime]]);
                while ($step <= $count) {
                    $method = "upgrade{$step}";
                    if (method_exists($this, $method) && !commonModel::getCount($this->tableName, ["name" => $method, "status" => 1])) { // 执行更新
                        try {
                            $this->{$method}();
                            commonModel::toAdd($this->tableName, ["name" => $method, "status" => 1, "create_time" => time()]);
                        } catch (\Exception $e) {
                            Tools::writeLog("更新脚本时出错{$method}：".var_export($e->getMessage() . "\r\n" . $e->getLine(), true) . "\r\n" . var_export($e->getTraceAsString(), true), "script.txt");
                            if(strpos($e->getMessage(), "Column already exists") !== false){
                                commonModel::toAdd($this->tableName, ["name" => $method, "status" => 1, "create_time" => time()]);
                            }
                        }
                    }
                    $step++;
                };
            }
        }catch (\Exception $e){
            $this->returnData = ErrorCode::code("try_error", $e->getMessage());
            $this->returnData["msg"] = iconv("GBK", "UTF-8",$this->returnData["msg"]);
        }
        return $this->return_result($this->returnData);
    }

    public function upgrade16(){
        Db::query("CREATE TABLE `tr_rental_outlets` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `number_id` varchar(10) not null COMMENT '网点ID',
    `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID',
    `name` varchar(60) DEFAULT NULL COMMENT '网点名',
    `mobile` varchar(15) NOT NULL DEFAULT '' COMMENT '联系电话',
    `address` varchar(255) NOT NULL DEFAULT '' COMMENT '地址',
    `province_code` int(11) NOT NULL DEFAULT '0',
    `city_code` int(11) NOT NULL DEFAULT '0',
    `area_code` int(11) NOT NULL DEFAULT '0',
    `longitude` varchar(20) NOT NULL DEFAULT '' COMMENT '经度',
    `latitude` varchar(20) NOT NULL DEFAULT '' COMMENT '纬度',
    `score` int(11) NOT NULL DEFAULT '5' COMMENT '店铺评分',
    `pic_id` text NOT NULL COMMENT '门店实景图',
    `business_hours` varchar(125) NOT NULL DEFAULT '' COMMENT '营业时间',
    `service_fee` decimal(6,2) DEFAULT '0.00' COMMENT '上门服务费',
    `deliver_range` int(10) DEFAULT 0 COMMENT '送车范围',
    `status` tinyint(4) unsigned default 1 COMMENT '状态；1可用，2禁用',
    `create_time` char(10) DEFAULT NULL COMMENT '创建时间',
    `update_time` char(10) DEFAULT NULL COMMENT '更新时间',
   PRIMARY KEY (`id`),
   key (`mall_id`),
   key (`number_id`),
   key (`status`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='租车网点表';");
        Db::query("CREATE TABLE `tr_outlets_car` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `outlet_id` int(10) unsigned not null COMMENT '网点',
    `car_id` int(10) unsigned not null COMMENT '车辆ID',
    `price` decimal(7,2) DEFAULT '0.00' COMMENT '日均价',
    `week_price` text DEFAULT null COMMENT '周价格',
    `special_price` text DEFAULT null COMMENT '特殊价',
    `stock` int(10) DEFAULT 0 COMMENT '总车辆',
    `over_stock` int(10) DEFAULT 0 COMMENT '剩余车辆',
    `status` tinyint(4) unsigned default 1 COMMENT '状态；1可用，2禁用',
    `update_time` char(10) DEFAULT NULL COMMENT '更新时间',
    `create_time` char(10) DEFAULT NULL COMMENT '创建时间',
   PRIMARY KEY (`id`),
   key (`outlet_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='网点的车表';");
        Db::query("alter table tr_order modify column `type` tinyint(3) unsigned DEFAULT 1 COMMENT '类型；1机场接送，2巴士路线，3专车接送，4包车路线, 5租车网点'");
        Db::query("CREATE TABLE `tr_outlets_surcharge` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID',
    `name` varchar(60) DEFAULT NULL COMMENT '名称',
    `price` decimal(7,2) DEFAULT '0.00' COMMENT '价格',
    `desc` varchar(500) DEFAULT null COMMENT '简要描述',
    `mode` tinyint(1) unsigned default 1 COMMENT '模式；1默认，2自选',
    `status` tinyint(1) unsigned default 1 COMMENT '状态；1可用，2禁用',
    `update_time` char(10) DEFAULT NULL COMMENT '更新时间',
    `create_time` char(10) DEFAULT NULL COMMENT '创建时间',
   PRIMARY KEY (`id`),
   key (`mall_id`),
   key (`status`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='网点附加费用表';");
        Db::query("CREATE TABLE `tr_outlets_agreement` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID',
    `name` varchar(60) DEFAULT NULL COMMENT '名称',
    `content` varchar(500) DEFAULT null COMMENT '内容',
    `status` tinyint(1) unsigned default 1 COMMENT '状态；1可用，2禁用',
   PRIMARY KEY (`id`),
   key (`mall_id`),
   key (`status`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='网点协议表'");
        Db::query("alter table tr_order modify column `reserve_time` varchar(50) DEFAULT NULL COMMENT '预约时间'");
        Db::query("CREATE TABLE `tr_outlets_search` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID',
    `user_id` int(10) DEFAULT 0 COMMENT '用户id',
    `content` text DEFAULT null COMMENT '内容',
   PRIMARY KEY (`id`),
   key (`mall_id`),
   key (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='网点搜索记录表';");
        Db::query("INSERT INTO `tr_wx_path` VALUES ('11', '网点租车', 'pages/rentCar/rentCar', '1');");
        Db::query("CREATE TABLE `tr_order_outlets_detail` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `order_id` int(10) COMMENT '订单id',
  `take_id` int(3) DEFAULT null COMMENT '取车网点id',
  `oc_id` int(3) DEFAULT null COMMENT '网点车的id',
  `also_id` int(3) DEFAULT null COMMENT '还车网点id',
  `serve` text DEFAULT null COMMENT '服务',
  `plate_number` varchar(20) COMMENT '车牌号',
  `start_time` varchar(30) DEFAULT null COMMENT '开始时间',
  `end_time` varchar(30) DEFAULT null COMMENT '结束时间',
  PRIMARY KEY (`id`),
  key (`order_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='订单详情表';");
        Db::query("CREATE TABLE `tr_car_list` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID',
  `car_id` int(2) unsigned COMMENT '车ID',
  `plate_number` varchar(20) COMMENT '车牌号',
  `attr_id` int(2) unsigned DEFAULT 0 COMMENT '所属id',
  `type` tinyint(3) unsigned DEFAULT null COMMENT '类型；1机场接送，2巴士路线，3专车接送，4包车路线, 5租车网点',
  `use` tinyint(3) unsigned DEFAULT 0 COMMENT '0空闲，1占用',
  PRIMARY KEY (`id`),
  KEY (`car_id`),
  KEY `relate` (`type`, `attr_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='车列表';");
        Db::query("INSERT INTO `tr_car_list` (`id`, `mall_id`, `car_id`, `plate_number`, `attr_id`, `type`, `use`) VALUES ('1', '1', '1', '粤BFA4648', '0', NULL, '0');");
    }

    public function upgrade15(){
        Db::query("alter table tr_saas_setting add `open_app_id` varchar(25) DEFAULT NULL COMMENT '第三方平台appId'");
        Db::query("alter table tr_saas_setting add `open_app_secret` varchar(35) DEFAULT NULL COMMENT '第三方平台appSecret'");
        Db::query("alter table tr_saas_setting add `msg_verify_token` varchar(50) DEFAULT NULL COMMENT '消息校验Token'");
        Db::query("alter table tr_saas_setting add `encoding_key` varchar(50) DEFAULT NULL COMMENT '消息加解密Key'");
    }

    public function upgrade14(){
        Db::query("alter table tr_line_menu add `sort` int(10) unsigned NOT NULL DEFAULT '0' COMMENT '排序'");
        Db::query("DROP INDEX ind_user_id ON tr_user_token");
        Db::query("alter table tr_user_token add index (`token`)");
    }

    // 2020-0316
    public function upgrade13(){
        Db::query("alter table tr_admin add `auth_id` varchar(15) DEFAULT 0 COMMENT '授权UID'");
        Db::query("alter table tr_mall add `instance_id` int(10) unsigned NOT NULL DEFAULT 0 COMMENT '实例ID'");
        Db::query("alter table tr_mall add `source` varchar(20)  DEFAULT NULL COMMENT '来源'");
        Db::query("alter table tr_admin add index (`auth_id`)");

        Db::query("alter table tr_saas_setting add `secret_id` varchar(40) DEFAULT NULL COMMENT '腾讯云访问密钥ID'");
        Db::query("alter table tr_saas_setting add `secret_key` varchar(40) DEFAULT NULL COMMENT '腾讯云访问密钥KEY'");
        Db::query("alter table tr_saas_setting add `bucket` varchar(35) DEFAULT NULL COMMENT '腾讯云存储桶名'");
        Db::query("alter table tr_saas_setting add `region` varchar(20) DEFAULT NULL COMMENT '存储桶地域'");
    }

    public function upgrade12(){
        Db::query("CREATE TABLE `tr_mall` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(64) DEFAULT NULL COMMENT '商城名称',
  `manager_id` int(10) unsigned NOT NULL COMMENT '用户ID',
  `is_delete` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否删除',
  `is_disable` tinyint(1) NOT NULL DEFAULT '0' COMMENT '是否禁用',
  `expired_time` char(10) DEFAULT '0' COMMENT '到期时间',
  `create_time` char(10) DEFAULT NULL COMMENT '创建时间',
  `update_time` char(10) DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`),
  KEY `ind_manager_id` (`manager_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='商城'");
        Db::query("CREATE TABLE `tr_saas_setting` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `logo` varchar(50) DEFAULT NULL COMMENT 'logo',
  `site_title` varchar(50) DEFAULT NULL COMMENT '站点标题',
  `seo_title` varchar(100) DEFAULT NULL COMMENT '网站seo的标题',
  `copyright` varchar(200) DEFAULT NULL COMMENT '版权信息',
  `sms_id` varchar(30) DEFAULT NULL COMMENT '短信appid',
  `sms_secret` varchar(60) DEFAULT NULL COMMENT '短信appkey',
  `sms_sign` varchar(60) DEFAULT NULL COMMENT '短信签名',
  `sms_code` varchar(20) DEFAULT NULL COMMENT '验证码模板ID',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='saas配置'");
        Db::query("CREATE TABLE `tr_wxapp_upgrade` (
    `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
    `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID',
    `version` varchar(20) DEFAULT NULL COMMENT '版本号',
    `remarks` text COMMENT '版本说明',
    `title` varchar(255) DEFAULT NULL COMMENT '日志标题',
    `content` text COMMENT '更新说明',
    `create_time` varchar(20) DEFAULT NULL COMMENT '创建时间',
   PRIMARY KEY (`id`),
   key (`mall_id`),
   KEY (`version`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='小程序版本更新表'");

        Db::query("alter table tr_admin add `avatar` varchar(100) DEFAULT NULL COMMENT '头像'");
        Db::query("alter table tr_admin add `mobile` varchar(11) DEFAULT NULL COMMENT '手机号码'");
        Db::query("alter table tr_admin add `app_count` tinyint(2) unsigned DEFAULT 1 COMMENT '商城数量'");
        Db::query("alter table tr_admin add `remark` varchar(200) DEFAULT NULL COMMENT '备注'");
        Db::query("alter table tr_admin add `expired_time` char(10) DEFAULT NULL COMMENT '到期时间'");
        Db::query("alter table tr_admin add index (`username`)");
        Db::query("alter table tr_admin_session add `is_saas` char(1) DEFAULT '0' COMMENT 'saas状态'");
        Db::query("alter table tr_admin_session add `is_admin` char(1) DEFAULT '0' COMMENT '商城状态'");
        Db::query("alter table tr_operate_log add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_operate_log add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_user add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_user add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_user_token add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_user_token add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_user_contact add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_user_contact add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_driver add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_driver add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_verifier add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_verifier add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_car_type add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_car_type add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_car add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_car add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_airport add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_airport add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_airport_line add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_airport_line add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_buses_line add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_buses_line add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_classes_cache add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_classes_cache add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_car_line add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_car_line add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_order add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_order add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_order_commission add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_order_commission add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_invoices add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_invoices add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_personal_invoice add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_personal_invoice add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_transfer add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_transfer add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_refund add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_refund add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_coupon add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_coupon add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_user_coupon add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_user_coupon add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_resource add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_resource add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_line_menu add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_line_menu add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_banner add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_banner add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_banner change size image_size varchar(90) COMMENT '尺寸'");
        Db::query("alter table tr_line_menu add `image_size` varchar(90) COMMENT '尺寸'");
        Db::query("alter table tr_article_type add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_article_type add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_article add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_article add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_form_id add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_form_id add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_sms_record add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_sms_record add `code` varchar(10) DEFAULT NULL COMMENT '验证码'");
        Db::query("alter table tr_sms_record add `status` tinyint(2) unsigned default 2 COMMENT '状态；1未使用，2已使用'");
        Db::query("alter table tr_sms_record add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_sms_record add index (`status`)");
        Db::query("alter table tr_sms_record modify column `create_time` varchar(20) DEFAULT NULL COMMENT '创建时间'");
        Db::query("alter table tr_cache add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_cache add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_system_set add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_system_set add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_reason add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_reason add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_cron_job add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_cron_job add index `ind_mall_id` (`mall_id`)");
        Db::query("alter table tr_vehicle_line add `mall_id` int(10) unsigned DEFAULT 0 COMMENT '所属商城ID'");
        Db::query("alter table tr_vehicle_line add index `ind_mall_id` (`mall_id`)");
        try {
            Db::query("DROP INDEX ind_nickname ON tr_user");
            Db::query("DROP INDEX mobile ON tr_user");
            Db::query("DROP INDEX email ON tr_user");
            Db::query("alter table tr_user add index (`mobile`)");
            Db::query("DROP INDEX ind_time ON tr_classes_cache");
            Db::query("DROP INDEX ind_type ON tr_form_id");
            Db::query("DROP INDEX ind_type ON tr_resource");
            Db::query("DROP INDEX ind_url ON tr_resource");
            Db::query("DROP INDEX mobile ON tr_driver");
            Db::query("DROP INDEX email ON tr_driver");
            Db::query("alter table tr_driver add index (`mobile`)");
            Db::query("alter table `tr_user` drop column `is_driver`");
            Db::query("alter table `tr_user` drop column `is_verifier`");
        }catch (\Exception $e){}
        trOperateLog::where("mall_id", 0)->update(["mall_id" => 1]);
        trUser::where("mall_id", 0)->update(["mall_id" => 1]);
        $id = trAdmin::where("username", "admin")->value("id");
        Db::query("INSERT INTO `tr_mall` VALUES ('1', '租车商城', $id, 0, 0, '0', ".time().", ".time().");");
        Db::query("update `tr_admin` set `app_count` = NULL where `id` = {$id};");
        trUserToken::where("mall_id", 0)->update(["mall_id" => 1]);
        commonModel::toUpdate(contactTable, ["mall_id" => 1], ["mall_id" => 0]);
        trDriver::where("mall_id", 0)->update(["mall_id" => 1]);
        commonModel::toUpdate(verifierTable, ["mall_id" => 1], ["mall_id" => 0]);
        trCarType::where("mall_id", 0)->update(["mall_id" => 1]);
        trCar::where("mall_id", 0)->update(["mall_id" => 1]);
        trAirport::where("mall_id", 0)->update(["mall_id" => 1]);
        trAirportLine::where("mall_id", 0)->update(["mall_id" => 1]);
        trBusesLine::where("mall_id", 0)->update(["mall_id" => 1]);
        commonModel::toUpdate(trClassesCache::$name, ["mall_id" => 1], ["mall_id" => 0]);
        trCarLine::where("mall_id", 0)->update(["mall_id" => 1]);
        trOrder::where("mall_id", 0)->update(["mall_id" => 1]);
        commonModel::toUpdate(orderCommissionTable, ["mall_id" => 1], ["mall_id" => 0]);
        trInvoices::where("mall_id", 0)->update(["mall_id" => 1]);
        commonModel::toUpdate(personalInvoiceTable, ["mall_id" => 1], ["mall_id" => 0]);
        commonModel::toUpdate(transferTable, ["mall_id" => 1], ["mall_id" => 0]);
        commonModel::toUpdate(refundTable, ["mall_id" => 1], ["mall_id" => 0]);
        trCoupon::where("mall_id", 0)->update(["mall_id" => 1]);
        commonModel::toUpdate(userCouponTable, ["mall_id" => 1], ["mall_id" => 0]);
        trResource::where("mall_id", 0)->update(["mall_id" => 1]);
        commonModel::toUpdate(lineMenuTable, ["mall_id" => 1], ["mall_id" => 0]);
        commonModel::toUpdate(bannerTable, ["mall_id" => 1], ["mall_id" => 0]);
        trArticle::where("mall_id", 0)->update(["mall_id" => 1]);
        trArticleType::where("mall_id", 0)->update(["mall_id" => 1]);
        commonModel::toUpdate(formIdTable, ["mall_id" => 1], ["mall_id" => 0]);
        trCache::where("mall_id", 0)->update(["mall_id" => 1]);
        trSystemSet::where("mall_id", 0)->update(["mall_id" => 1]);
        trReason::where("mall_id", 0)->update(["mall_id" => 1]);
        commonModel::toUpdate(cronJobTable, ["mall_id" => 1], ["mall_id" => 0]);
        trVehicleLine::where("mall_id", 0)->update(["mall_id" => 1]);
    }

    // 更新 - 2020-01-15
    public function upgrade11(){
        Db::query("CREATE TABLE `tr_personal_invoice` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `user_id` int(10) unsigned NOT NULL COMMENT '用户ID',
  `type` tinyint(3) unsigned DEFAULT 1 COMMENT '类型；1个人，2企业',
  `head_name` varchar(60)  COMMENT '发票抬头',
  `duty_number` varchar(30) COMMENT '税号',
  `create_time` char(10) NOT NULL COMMENT '创建时间',
  PRIMARY KEY (`id`),
  KEY `ind_user_id` (`user_id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='个人发票表'");
        Db::query("alter table tr_refund add `refund_fee` decimal(8,2) DEFAULT '0.000' COMMENT '退款手续费'");
        Db::query("alter table tr_order add `refund_fee` decimal(8,2) DEFAULT '0.000' COMMENT '退款手续费'");
        Db::query("alter table tr_invoices modify column `mobile` varchar(20) COMMENT '手机号码'");
    }

    // 更新 - 2019-11-22
    public function upgrade10(){
        Db::query("alter table tr_buses_line add `ticketing_time` varchar(50) COMMENT '售票时间'");
    }

    // 更新 - 2019-11-22
    public function upgrade9(){
        Db::query("alter table tr_user_coupon add `type` tinyint(1) DEFAULT NULL COMMENT '类型，1：机场接送、2：巴士路线、3专车接送，4包车路线、0通用'");
        Db::query("alter table tr_user_coupon add `mold` tinyint(3) NOT NULL DEFAULT '1' COMMENT '获得方式 1：普通类型 2：推荐类型 3：被推荐类型'");
        Db::query("alter table tr_user_coupon add `name` varchar(150) NOT NULL COMMENT '名称'");
        Db::query("alter table tr_user_coupon add `condition` varchar(2) DEFAULT NULL COMMENT '条件'");
        Db::query("alter table tr_user_coupon add `amount` float DEFAULT '0' COMMENT '优惠额度'");
        Db::query("alter table tr_user_coupon add `content` text COMMENT '条件的内容'");
        Db::query("alter table tr_user_coupon add `get_time` char(10) COMMENT '领取时间'");
        Db::query("alter table tr_user_coupon add `end_time` char(10) COMMENT '结束时间'");
        Db::query("alter table tr_user_coupon modify column `status` tinyint(1) unsigned DEFAULT 1 COMMENT '状态，1：可用，2：已使用'");

        $data = commonModel::getFields(userCouponTable, "*", [], false);
        if(count($data)){
            foreach ($data as $item){
                $coupon = (isset($item["coupon"]) && $item["coupon"]) ? unserialize($item["coupon"]) : [];
                if(!empty($coupon)){
                    $update = [
                        "type" => isset($coupon["type"]) ? $coupon["type"] : 0,
                        "name" => isset($coupon["name"]) ? $coupon["name"] : "",
                        "condition" => isset($coupon["condition"]) ? $coupon["condition"] : "",
                        "amount" => isset($coupon["amount"]) ? $coupon["amount"] : 0,
                        "content" => isset($coupon["content"]) ? $coupon["content"] : "",
                        "mold" => isset($coupon["mold"]) ? $coupon["mold"] : "",
                        "get_time" => $item["time"],
                        "end_time" => isset($coupon["timeTo"]) ? (is_numeric($coupon["timeTo"]) ? $coupon["timeTo"] : strtotime($coupon["timeTo"])) : time(),
                    ];
                    if($item["status"] > "1"){
                        $update["status"] = 2;
                    }elseif($item["status"] = "0"){
                        $update["status"] = 2;
                    }
                    commonModel::toUpdate(userCouponTable, $update, ["id" => $item["id"]]);
                }
            }
        }
        unset($data);
        $couponModel = new trCoupon();
        $couponData = $couponModel->getFields("*", ["status" => 1, "mold" => 1], false);
        foreach ($couponData as $index => $couponDatum) {
            CouponLogic::addUserCouponByTemplate($couponDatum["id"], $couponDatum);
        }

        Db::query("alter table `tr_user_coupon` drop column `coupon`");
        Db::query("alter table `tr_user_coupon` drop column `time`");
    }

    // 更新 - 2019-11-22
    public function upgrade9_(){
        Db::query("alter table tr_user_coupon add `end_time` char(10) COMMENT '结束时间',");
        $data = commonModel::getFields(userCouponTable, "*", [["status", ">", "1"]], false);
        if(count($data)){
            foreach ($data as $item){
                commonModel::toUpdate(userCouponTable, ["status" => 2], ["id" => $item["id"]]);
            }
        }
        commonModel::toUpdate(userCouponTable, ["status" => 2], ["status" => "0"]);
    }

    // 更新 - 2019-11-12
    public function upgrade8(){
        Db::query("alter table tr_user add `share_qr` varchar(225) DEFAULT NULL COMMENT '分享专属二维码'");
        Db::query("alter table tr_coupon add `mold` tinyint(3) NOT NULL DEFAULT '1' COMMENT '获得方式 1：普通类型 2：推荐类型 3：被推荐类型'");
        Db::query("alter table tr_buses_line add `ticket_deadline` varchar(4) NOT NULL DEFAULT '0' COMMENT '售票截止时间，单位分钟'");
    }

    // 更新 - 2019-10-22
    public function upgrade7(){
        Db::query("CREATE TABLE `tr_verifier` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `nickname` varchar(50) COMMENT '姓名',
  `gender` tinyint(3) unsigned NOT NULL DEFAULT 1 COMMENT '性别：1男；2女',
  `prefix` varchar(3) DEFAULT 86 COMMENT '手机前缀',
  `mobile` char(11) COMMENT '手机号码',
  `email` varchar(30) COMMENT '邮箱',
  `openid` varchar(50) COMMENT '微信',
  `id_card` varchar(25) COMMENT '身份证',
  `remark` varchar(100) COMMENT '备注信息',
  `status` tinyint(3) unsigned DEFAULT 2 COMMENT '状态：1正常；2休息；3注销',
  `add_time` char(10) NOT NULL COMMENT '添加时间',
  PRIMARY KEY (`id`),
  UNIQUE (`openid`),
  UNIQUE (`mobile`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4 COMMENT='核销员表';");
        Db::query("DROP INDEX ind_nickname ON tr_driver");
        Db::query("alter table tr_user add `user_type` char(1) DEFAULT 0 COMMENT '用户身份；0普通，1司机，2核销员'");
        usleep(10000); // 注意休眠，不然下面可能会查不到字段
        $userModel = new trUser();
        $data = $userModel->getColumn("id", ["is_driver" => "1"]);
        $userModel::where([["id", "in", $data]])->update(["user_type" => "1"]);
        Db::query("alter table `tr_user` drop column `is_driver`");
    }

    // 更新 - 2019-10-21  - 修改巴士表名和引用的地方
    public function upgrade6(){
        Db::query("alter table tr_enterprise_line rename to tr_buses_line"); // 表名重命名
        $data = Db::name(trClassesCache::$name)->where("key", "like", "enterpriseLine%")->select(); // 修改班次数据
        foreach ($data as $item) {
            $key = str_replace("enterpriseLineClasses_", "busesLineClasses_", $item["key"]);
            trClassesCache::del($item["key"]);
            trClassesCache::toSave(unserialize($item["value"]), $key, ["time" => $item["time"]]);
        }
        $busesModel = new trBusesLine();
        $busesData = $busesModel->getColumn("id");
        trClassesCache::delByFilter([["time", "exp", Db::raw("is null")], ["key", "not in", "busesLineClasses_".implode(",busesLineClasses_", $busesData)]]);
    }

    // 更新 - 2019-10-16
    public function upgrade5(){
        $enterpriseData = trSystemSet::getValue("enterpriseRemarks");
        $vehicleData = trSystemSet::getValue("vehicleRemarks");
        $res = Tools::saveFileToDatabase(tome_dia("/attachment/default/hotline-1.jpg", false));
        if(!isset($vehicleData["hotLineBanner"])) {
            $setting = [
                "vehicleRemarks" => $vehicleData["vehicleRemarks"],   //包车路线备注
                "vehicleAlias" => $vehicleData["vehicleAlias"],   //包车线路备注
                "hotLineBanner" => $res["id"],
                "hotLineRemark" => "热门线路"
            ];
            trSystemSet::toSave($setting, "vehicleRemarks");
        }
        if(!isset($enterpriseData["hotLineBanner"])) {
            $setting = [
                "enterpriseRemarks" => $enterpriseData["enterpriseRemarks"],   //巴士线路备注
                "enterpriseAlias" => $enterpriseData["enterpriseAlias"],   //巴士线路备注
                "hotLineBanner" => $res["id"],
                "hotLineRemark" => "热门线路"
            ];
            trSystemSet::toSave($setting, "enterpriseRemarks");
        }
    }

    // 更新 - 2019-10-08
    public function upgrade4(){
        $airportData = trSystemSet::getValue("airportRemarks");
        $enterpriseData = trSystemSet::getValue("enterpriseRemarks");
        $vehicleData = trSystemSet::getValue("vehicleRemarks");
        $carData = trSystemSet::getValue("carRemarks");
        $cancelTime = trSystemSet::getValue("orderCancelTime");
        $orderRemindData = trSystemSet::getValue("orderRemindSetting");
        $remindTpl = trSystemSet::getValue("smsOrderRemindTpl"); // 订单支付成功通知分配单
        if(!isset($carData["carAlias"])) {
            $setting = ["carAlias" => "专车接送"];
            if(!isset($carData["carRemarks"])){
                $setting["carRemarks"] = "";
            }
            trSystemSet::toSave($setting, "carRemarks");
        }
        if(!isset($vehicleData["vehicleAlias"])) {
            $setting = ["vehicleAlias" => "包车线路"];
            if(!isset($carData["vehicleRemarks"])){
                $setting["vehicleRemarks"] = "";
            }
            trSystemSet::toSave($setting, "vehicleRemarks");
        }
        if(!isset($enterpriseData["enterpriseAlias"])) {
            $setting = ["enterpriseAlias" => "巴士线路"];
            if(!isset($carData["enterpriseRemarks"])){
                $setting["enterpriseRemarks"] = "";
            }
            trSystemSet::toSave($setting, "enterpriseRemarks");
        }
        if(!isset($airportData["airportAlias"])) {
            $setting = ["airportAlias" => "机场线路"];
            if(!isset($carData["airportRemarks"])){
                $setting["airportRemarks"] = "";
            }
            trSystemSet::toSave($setting, "airportRemarks");
        }
        if(empty($cancelTime)) {
            trSystemSet::toSave(30, "orderCancelTime");
        }
        if(empty($remindTpl)) {
            trSystemSet::toSave(["remindTpl" => "", "remindTplStatus" => 0], "smsOrderRemindTpl");
        }
        if(empty($orderRemindData)) {
            for ($i = 1; $i <= 5; $i++) {
                $data["remind$i"] = ["status" => 0, "value" => "",];
            }
            trSystemSet::toSave($data, "orderRemindSetting");
        }
        Db::query("alter table tr_operate_log add `target` varchar(20) default NULL COMMENT '目标，标记'");
    }

    // 更新 - 2019-10-05
    public function upgrade3(){
        Db::query("alter table tr_order add `long_lat_from` varchar(32) DEFAULT NULL COMMENT '出发地的经纬度'");
        Db::query("alter table tr_order add `long_lat_to` varchar(32) DEFAULT NULL COMMENT '目的地的经纬度'");
    }

    // 更新 - 2019-09-29
    public function upgrade2(){
        Db::query("alter table tr_airport_line add `charge_type` tinyint(3) unsigned DEFAULT 0 COMMENT '计费模式；0: 按人头, 1: 按车辆'");
        Db::query("alter table tr_car_line add `charge_type` tinyint(3) unsigned DEFAULT 0 COMMENT '计费模式；0: 按人头, 1: 按车辆'");
    }

    // 更新 - 2019-09-25
    public function upgrade1(){
        Db::query("DROP TABLE IF EXISTS `tr_wx_path`;");
        Db::query("CREATE TABLE `tr_wx_path` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`title` varchar(20) DEFAULT NULL COMMENT '标题',
`url` varchar(90) DEFAULT NULL COMMENT '页面url',
`show` tinyint(1) unsigned DEFAULT 1 COMMENT '状态：1显示；2隐藏',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='微信小程序路径';");
        Db::query("INSERT INTO `tr_wx_path` (`id`, `title`, `url`) VALUES ('1', '巴士路线', 'pages/route/daily/index/index');");
        Db::query("INSERT INTO `tr_wx_path` (`id`, `title`, `url`) VALUES ('2', '巴士热门路线', 'pages/route/daily/hotRoute/hotRoute');");
        Db::query("INSERT INTO `tr_wx_path` (`id`, `title`, `url`) VALUES ('3', '机场接送', 'pages/route/airport/airport');");
        Db::query("INSERT INTO `tr_wx_path` (`id`, `title`, `url`) VALUES ('4', '专车接送', 'pages/route/special/special');");
        Db::query("INSERT INTO `tr_wx_path` (`id`, `title`, `url`, `show`) VALUES ('5', '包车路线', 'pages/route/fixed/index/index', '2');");
        Db::query("INSERT INTO `tr_wx_path` (`id`, `title`, `url`, `show`) VALUES ('6', '包车热门路线', 'pages/route/fixed/hotRoute/hotRoute', '2');");
        Db::query("INSERT INTO `tr_wx_path` (`id`, `title`, `url`) VALUES ('7', '我的优惠券列表', 'pages/center/coupon/coupon');");
        Db::query("INSERT INTO `tr_wx_path` (`id`, `title`, `url`) VALUES ('8', '我的发票列表', 'pages/center/invoice/index/index');");
        Db::query("INSERT INTO `tr_wx_path` (`id`, `title`, `url`) VALUES ('9', '我的联系人列表', 'pages/center/liaison/liaison');");
        Db::query("INSERT INTO `tr_wx_path` (`id`, `title`, `url`) VALUES ('10', '关于我们', 'pages/center/aboutUs/aboutUs');");
        commonModel::toUpdate(wxPathTable, ["show" => 1], ["show" => 2]);
    }
}
